package com.vf.cloud.rendering.common.scheduled;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.vf.cloud.rendering.api.service.IDownloadClient;
import com.vf.cloud.rendering.common.constant.Cache;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@EnableScheduling
public class SceneScheduled {
	
	private boolean isStop=true;;

	
	@Autowired
	private IDownloadClient iDownloadClient;
	
	@Scheduled(fixedRate = 60000*2)
	@Async
	public void scheduled() {
		try {
			if( null==Cache.dispatch) {
				return;
			}
			if(isStop) {
				isStop=false;
				String result=doGet();
				if(!StrKit.isBlank(result)) {
					JSONObject RJSONObject=JSONObject.parseObject(result);
					if(RJSONObject!=null && RJSONObject.containsKey("code") && RJSONObject.getInteger("code")==200 && RJSONObject.containsKey("result")) {
						JSONArray jsonArray=RJSONObject.getJSONArray("result");
						if(jsonArray!=null&&jsonArray.size()>0) {
							for(Object o:jsonArray) {
								iDownloadClient.download(o.toString());
							}
						}
					}
				}
			}
			isStop=true;
		}catch (Exception e) {
			log.error("同步场景异常:",e);
		}finally {
			isStop=true;
		}
	}

	public String doGet() throws Exception {
		// 输入流
		InputStream is = null;
		BufferedReader br = null;
		String result = null;
		// 创建httpClient实例
		HttpClient httpClient = new HttpClient();
		// 设置http连接主机服务超时时间：15000毫秒
		// 先获取连接管理器对象，再获取参数对象,再进行参数的赋值
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
		// 创建一个Get方法实例对象
		GetMethod getMethod = new GetMethod(String.format("http://%s:8880/biz/terminal/scene/syn?mac=%s", Cache.dispatch.getIp(),Cache.local.getMac()));
		// 设置get请求超时为60000毫秒
		getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
		// 设置请求重试机制，默认重试次数：3次，参数设置为true，重试机制可用，false相反
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
		try {
			// 执行Get方法
			int statusCode = httpClient.executeMethod(getMethod);
			// 判断返回码
			if (statusCode != HttpStatus.SC_OK) {
				log.error("Method faild: " + getMethod.getStatusLine());
			} else {
				// 通过getMethod实例，获取远程的一个输入流
				is = getMethod.getResponseBodyAsStream();
				// 包装输入流
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

				StringBuffer sbf = new StringBuffer();
				// 读取封装的输入流
				String temp = null;
				while ((temp = br.readLine()) != null) {
					sbf.append(temp).append("\r\n");
				}
				result = sbf.toString();
			}

		} catch (IOException e) {
			log.error("Method faild: " + e.getMessage());
			throw e;
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 释放连接
			getMethod.releaseConnection();
		}
		return result;
	}

}
